<?php
declare(strict_types=1);

namespace App\Controllers;

use Core\Controller;
use PDO;

class User extends Controller
{
    /**
     * 显示用户注册表单
     */
    public function register()
    {
        // 如果用户已登录，重定向到首页
        if ($this->getCurrentUser()) {
            redirect('/');
        }
        
        $data = [
            'title'      => '用户注册',
            'csrf_token' => $this->app->generateCsrfToken(),
            'errors'     => $_SESSION['register_errors'] ?? [],
            'old'        => $_SESSION['register_old'] ?? []
        ];
        
        // 清除会话中的临时错误和旧输入
        unset($_SESSION['register_errors'], $_SESSION['register_old']);
        
        $this->render('user/register', $data);
    }
    /**
     * 用户注册
     */
    public function register1(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            $this->app->json(['error' => '仅支持 POST 请求'], 405);
            return;
        }

        // 验证 CSRF 令牌
        if (!$this->app->validateCsrfToken()) {
            $this->app->json(['error' => '无效的 CSRF 令牌'], 403);
            return;
        }

        // 验证输入数据
        $validation = $this->app->validate([
            'username' => 'required|min:3|max:20',
            'password' => 'required|min:6|max:32',
            'email'    => 'required|email',
            'confirm_password' => 'required'
        ]);

        if (!$validation['valid']) {
            $this->app->json([
                'success' => false,
                'errors' => $validation['errors']
            ], 400);
            return;
        }

        $data = $validation['data'];
        
        // 验证两次密码是否一致
        if ($data['password'] !== $data['confirm_password']) {
            $this->app->json([
                'success' => false,
                'error' => '两次输入的密码不一致'
            ], 400);
            return;
        }

        // 检查用户名/邮箱是否已存在
        $stmt = $this->app->query(
            "SELECT id FROM users WHERE username = :username OR email = :email",
            [
                'username' => $data['username'],
                'email' => $data['email']
            ]
        );

        if ($stmt->fetch()) {
            $this->app->json([
                'success' => false,
                'error' => '用户名或邮箱已被注册'
            ], 409);
            return;
        }

        try {
            // 密码哈希加密
            $hashedPassword = password_hash($data['password'], PASSWORD_DEFAULT);
            
            // 插入新用户
            $userId = $this->app->insert('users', [
                'username' => $data['username'],
                'password' => $hashedPassword,
                'email' => $data['email']
            ]);

            if (!$userId) {
                throw new \RuntimeException('用户创建失败');
            }

            $this->app->json([
                'success' => true,
                'message' => '注册成功！请登录',
                'user_id' => $userId
            ]);
        } catch (\Throwable $e) {
            $this->app->json([
                'success' => false,
                'error' => '注册失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 用户登录
     */
    public function login(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            http_response_code(405);
            $this->app->json(['error' => '仅支持 POST 请求'], 405);
            return;
        }

        // 验证 CSRF 令牌
        if (!$this->app->validateCsrfToken()) {
            $this->app->json(['error' => '无效的 CSRF 令牌'], 403);
            return;
        }

        // 验证输入
        $validation = $this->app->validate([
            'identifier' => 'required', // 可以是用户名或邮箱
            'password' => 'required'
        ]);

        if (!$validation['valid']) {
            $this->app->json([
                'success' => false,
                'errors' => $validation['errors']
            ], 400);
            return;
        }

        $identifier = $validation['data']['identifier'];
        $password = $validation['data']['password'];

        try {
            // 查询用户（支持用户名或邮箱登录）
            $stmt = $this->app->query(
                "SELECT id, username, password FROM users 
                 WHERE username = :identifier OR email = :identifier",
                ['identifier' => $identifier]
            );

            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                $this->app->json([
                    'success' => false,
                    'error' => '用户名或邮箱不存在'
                ], 404);
                return;
            }

            // 验证密码
            if (!password_verify($password, $user['password'])) {
                $this->app->json([
                    'success' => false,
                    'error' => '密码错误'
                ], 401);
                return;
            }

            // 更新最后登录时间
            $this->app->update('users', [
                'last_login' => date('Y-m-d H:i:s')
            ], ['id' => $user['id']]);

            // 设置登录状态（使用会话）
            $_SESSION['user'] = [
                'id' => $user['id'],
                'username' => $user['username'],
                'logged_in' => true,
                'login_time' => time()
            ];

            $this->app->json([
                'success' => true,
                'message' => '登录成功！',
                'user' => [
                    'id' => $user['id'],
                    'username' => $user['username']
                ]
            ]);
        } catch (\Throwable $e) {
            $this->app->json([
                'success' => false,
                'error' => '登录过程出错: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 获取当前登录用户信息
     */
    public function profile(): void
    {
        if (empty($_SESSION['user']) || empty($_SESSION['user']['logged_in'])) {
            $this->app->json([
                'success' => false,
                'error' => '未登录'
            ], 401);
            return;
        }

        try {
            $stmt = $this->app->query(
                "SELECT id, username, email, avatar, bio, created_at, last_login 
                 FROM users WHERE id = :id",
                ['id' => $_SESSION['user']['id']]
            );

            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                session_destroy();
                $this->app->json([
                    'success' => false,
                    'error' => '用户不存在'
                ], 404);
                return;
            }

            // 移除敏感信息
            unset($user['password']);
            
            $this->app->json([
                'success' => true,
                'user' => $user
            ]);
        } catch (\Throwable $e) {
            $this->app->json([
                'success' => false,
                'error' => '获取用户信息失败: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 用户登出
     */
    public function logout(): void
    {
        session_destroy();
        $this->app->json([
            'success' => true,
            'message' => '已安全退出'
        ]);
    }
}